package com.mairuide.platmanager;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.Constant;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.menuinfo.MenuInfo;
import com.mairuide.menuinfo.MenuInfoService;
import com.mairuide.menuuser.MenuUserService;
import com.mairuide.platgroup.PlatGroup;
import com.mairuide.platgroup.PlatGroupService;
import com.mairuide.platgroupuser.PlatGroupUser;
import com.mairuide.platgroupuser.PlatGroupUserService;
import com.mairuide.platrole.PlatRole;
import com.mairuide.platrole.PlatRoleService;
import com.mairuide.platroleuser.PlatRoleUser;
import com.mairuide.platroleuser.PlatRoleUserService;


/**
 * 平台用户Controller
 * @author mh
 *
 */
@Controller
@RequestMapping("/platManager")
public class PlatManagerController extends BaseController  {
	
	@Resource
	private PlatManagerService platManagerService;
	
	@Resource
	private MenuInfoService menuInfoService;
	
	@Resource
	private MenuUserService menuUserService;
	
	@Resource
	private PlatRoleService platRoleService;
	
	@Resource
	private PlatRoleUserService platRoleUserService;
	
	@Resource
	private PlatGroupService platGroupService;
	
	@Resource
	private PlatGroupUserService platGroupUserService;


	/**
	 * 用户管理列表
	 * @param pageSupport
	 * @param model
	 * @param keywordType 关键字类型
	 * @param keyword 关键字
	 * @return
	 */
	@ModuleCode(pValue = "operations", value = "manageList")
	@RequestMapping(value = "/manageList", method = RequestMethod.GET)
	public String manageList (PageSupport pageSupport, ModelMap model, @RequestParam(defaultValue="0")Integer keywordType
			, @RequestParam(defaultValue="") String keyword) {
		
//		// 上级(非子账号代理商用自己，子账号代理商用上级)
		Page<PlatManager> page  = platManagerService.findManagerList4HeadQuarter(keywordType, keyword.trim(), pageSupport.getPage());
		model.addAttribute("page", page);
		model.addAttribute("keywordType", keywordType);
		model.addAttribute("keyword", keyword.trim());
		model.addAttribute("userType", 3);
		Map<String, List<MenuInfo>> secondLevelMenuMap = (Map<String, List<MenuInfo>>)request.getSession().getAttribute("secondLevelMenuMap");
		List<MenuInfo> firstLevelMenuList = (List<MenuInfo>)request.getSession().getAttribute("firstLevelMenuList");
		for(MenuInfo m : firstLevelMenuList){
			if("系统设置".equals(m.getMenuName())){
				List<MenuInfo> menuInfos = secondLevelMenuMap.get(String.valueOf(m.getMenuId()));
				if(menuInfos!=null&&menuInfos.size()>0){
					String menuUrl = menuInfos.get(0).getMenuUrl();
					if(menuUrl!=null&&!"/platManager/manageList".equals(menuUrl)){
						return "redirect:"+menuUrl;
					}
				}
			}
		}
		return "/platmanager/manageList";
	}
	
	/**
	 * 用户管理跳转到新增或修改的方法
	 * @param model
	 * @param id 用户ID
	 * @param userType 在列表查询时获得（1:代理商角色,2:运营中心部门,3:总部或总部下级部门）
	 * @return
	 */
	@RequestMapping(value="/manageForm", method=RequestMethod.GET)
	public Object manageForm(ModelMap model, Integer id, Integer userType) {
		PlatManager bean = null;
		if (id != null && id > 0) {
			bean = platManagerService.findOne(id);
		} else {
			bean = new PlatManager();
		}
		
		List<PlatRole> platRoleList = new LinkedList<PlatRole>();
		List<PlatGroup> platGroupList = null;
		Set<Integer> myPlatRoleIdSet = null;
		Set<Integer> myPlatGroupIdSet = null;
		if (userType == 3) {
			// 封闭部门
			platGroupList = platGroupService.findByGroupCodeStartingWith("HEADQUARTERS");
			// 封闭角色 
			Sort sort = new Sort(Direction.ASC, "roleId");
			Iterable<PlatRole> platRoleIterable = platRoleService.findAll(sort);
			Iterator<PlatRole> platRoleIterator = null;
			if (platRoleIterable != null) {
				platRoleIterator = platRoleIterable.iterator();
				while (platRoleIterator.hasNext()) {
					PlatRole role = platRoleIterator.next();
					platRoleList.add(role);
				}
			}
			
			// 修改操作时，再查询被修改人的角色和所在的部门
			if (id != null && id > 0) {
				List<PlatRoleUser> platRoleUserList = platRoleUserService.findByUserId(id);
				myPlatRoleIdSet = platRoleUserList.stream().map(r->r.getRoleId()).collect(Collectors.toSet());
				List<PlatGroupUser> platGroupUserList = platGroupUserService.findByUserId(id);
				myPlatGroupIdSet = platGroupUserList.stream().map(r->r.getGroupId()).collect(Collectors.toSet());
			}
		} else {
			platGroupList = new LinkedList<PlatGroup>();
			myPlatRoleIdSet = new HashSet<Integer>();
			myPlatGroupIdSet = new HashSet<Integer>();
		}
		
		model.addAttribute("userType", userType);
		model.addAttribute("platManager", bean);
		model.addAttribute("platRoleList", platRoleList);
		model.addAttribute("platGroupList", platGroupList);
		model.addAttribute("myPlatRoleIdSet", myPlatRoleIdSet);
		model.addAttribute("myPlatGroupIdSet", myPlatGroupIdSet);
		
		return "/platmanager/manageSaveForm";
	}
	
	/**
	 * 用户管理新增保存或修改保存的方法
	 * @param model
	 * @param platManager
	 * @param userType 用户分类  在列表查询时获得（1:代理商角色,2:运营中心部门,3:总部或总部下级部门）
	 * @param roleIds 所选的角色
	 * @param groupIds 所选的部门
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/manageForm", method=RequestMethod.POST)
	public Object doManageForm(ModelMap model, PlatManager platManager, Integer userType
			, int[] roleIds, int[] groupIds) throws Exception {
		
		PlatManager loginUser = getLoginUser();
		
		// 先去除前后空格
		platManager.setNickName(platManager.getNickName().trim());
		platManager.setLoginName(platManager.getLoginName().trim());
		platManager.setPhone(platManager.getPhone().trim());
		
		// 上级(非子账号代理商用自己，子账号代理商用上级)
		PlatManager superior = null;
		if (loginUser.getIsSubAccount() != null && loginUser.getIsSubAccount().intValue() == 1) {
			// 子账号， 找上级
			superior = platManagerService.findOne(loginUser.getSuperiorId());
		} else {
			// 上级，不变
			superior = loginUser;
		}
		
		if (userType == 1 || userType == 2) {
			platManager.setIsSubAccount(1);
			platManager.setSuperiorId(superior.getId());
		} else if (userType == 3) {
			platManager.setIsSubAccount(null);
		}
		
		if (platManager.getId() == null) {
			platManagerService.saveSubAccount(platManager, userType, roleIds, groupIds, loginUser);
		} else {
			platManagerService.updateSubAccount(platManager, userType, roleIds, groupIds, loginUser);
		}
		
		return "redirect:/platmanager/manageList";
	}
	
	/**
	 * 验证登录名唯一
	 * @param id 主键
	 * @param loginName 登录名
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/verifyLoginNameUnique", method=RequestMethod.POST)
	public Object verifyLoginNameUnique(Integer id, String loginName) {
		if (StringUtils.isEmpty(loginName)) {
			return ERROR("empty");
		} else {
			PlatManager oldPlatManager = platManagerService.verifyRepeatByIdAndLoginName(id, loginName.trim());
			
			if (oldPlatManager == null) {
				return SUCCESS();
			} else {
				return ERROR("repeat");
			}
		}
	}
	
	
	/**
	 * 修改密码跳转
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/modifyPassWordJump", method = RequestMethod.GET)
	public String modifyPassWordJump(ModelMap model) {
		return "/platmanager/reset_password_form";
	}
	
	/**
	 * 验证当前密码是否正确
	 * @param currentPassword
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/validateCurrentPassword", method = RequestMethod.POST)
	public Object validateCurrentPassword(String currentPassword) {
		Integer userId = getLoginUser().getId();
		PlatManager oldPlatManager = platManagerService.findOne(userId);
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		//当前输入密码md5加密
		String currentMD5Password = md5.encodePassword(currentPassword, null);
		//判断用户密码与输入密码是否匹配
		if(StringUtils.isNotEmpty(oldPlatManager.getPassword()) && oldPlatManager.getPassword().equals(currentMD5Password)) {
			return SUCCESS();
		}
		return ERROR("password mistake");
	}
	
	/**
	 * 修改密码
	 * @param currentPassword
	 * @param newPassword
	 * @param confirmPassword
	 * @return
	 */
	@RequestMapping(value = "/modifyPassWord", method = RequestMethod.POST)
	public String modifyPassWord(ModelMap model, String currentPassword, String confirmPassword) {
		Integer userId = getLoginUser().getId();
		PlatManager oldPlatManager = null;
		oldPlatManager = platManagerService.findOne(userId);
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		//当前输入密码md5加密
		String currentMD5Password = md5.encodePassword(currentPassword, null);
		//判断用户密码与输入密码是否匹配
		if(StringUtils.isNotEmpty(oldPlatManager.getPassword()) && oldPlatManager.getPassword().equals(currentMD5Password)) {
			oldPlatManager.setPassword(md5.encodePassword(confirmPassword, null));
			platManagerService.save(oldPlatManager);
			return "redirect:/logout";
		}else{
			return "redirect:/";
		}
	}
	
	/**
	 * 禁用或启用
	 */
	@ResponseBody
	@RequestMapping(value="/changeState", method=RequestMethod.POST)
	public Object changeState(Integer id, Integer state) {
		PlatManager oldPlatManager = platManagerService.findOne(id);
		oldPlatManager.setState(state);
		platManagerService.save(oldPlatManager);
		return SUCCESS();
	}
	
	/**
	 * 跳转-重置密码
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/resetPassWord", method = RequestMethod.GET)
	public String resetPassWord(ModelMap model, Integer id) {
		model.addAttribute("id", id);
		return "/platmanager/restPwdAlert";
	}
	
	/**
	 * 重置密码
	 * @param model
	 * @param platManager
	 * @return
	 */
	@RequestMapping(value = "/resetPassWord", method = RequestMethod.POST)
	public String doResetPassWord(ModelMap model,  PlatManager platManager) {
		if (getLoginUser() != null) {
			PlatManager oldPlatManager = null;
			if (platManager != null && platManager.getId() != null) {
				oldPlatManager = platManagerService.findOne(platManager.getId());
				Md5PasswordEncoder md5 = new Md5PasswordEncoder();
				String password = md5.encodePassword(Constant.PLATMANAGER_DEFAULT_PASSWORD, null);
				oldPlatManager.setPassword(password);
				platManagerService.save(oldPlatManager);
			}
		}
		return "redirect:/platmanager/manageList";
	}
	
	/**
	 * 跳转-功能授权
	 * @param model
	 * @param id 平台用户ID
	 * @param userType 在列表查询时获得（1:代理商角色,2:运营中心部门,3:总部或总部下级部门）
	 * @return
	 */
	@RequestMapping(value = "/menuAuthority", method = RequestMethod.GET)
	public String menuAuthority(ModelMap model, Integer id, Integer userType) {
		// 查询勾选范围的菜单权限
		List<MenuInfo> menuInfoList = menuInfoService.findByUserId(id);
		Set<Integer> authorityMenuIdSet = menuInfoList.stream().map(r->r.getMenuId()).collect(Collectors.toSet());
		
		// 查询显示范围的菜单权限
		List<MenuInfo> superiorMenuInfoList = null;
		if (userType == 1 || userType == 2) {
			// 代理商的列表和运营中心的列表传过来的被授权人是子账号，用显示上级的权限。
			PlatManager superior = null;
			PlatManager user = platManagerService.findOne(id);
			if (user.getIsSubAccount() != null && user.getIsSubAccount() == 1) {
				superior = platManagerService.findOne(user.getSuperiorId());
			} else {
				throw new RuntimeException("错误数据。");
			}
			
			// 查询上级拥有的菜单权限
			superiorMenuInfoList = menuInfoService.findByUserId(superior.getId());
		} else if (userType == 3) {
			// 总部的授权，显示所有的权限。
			superiorMenuInfoList = new LinkedList<MenuInfo>();
			Iterable<MenuInfo> menuInfoIterable = menuInfoService.findAll();
		    for (MenuInfo menu: menuInfoIterable) {
		    	superiorMenuInfoList.add(menu);
		    }
		} else {
			throw new RuntimeException("错误数据。");
		}
		if (superiorMenuInfoList.size()>0){
			//给菜单排序
			Collections.sort(superiorMenuInfoList, new Comparator<MenuInfo>() {
				@Override
				public int compare(MenuInfo o1, MenuInfo o2) {
					//升序
					return o1.getMenuIndex().compareTo(o2.getMenuIndex());
				}
			});
		}
		// 整理菜单层级（三级）
		List<MenuInfo> firstLevelMenuList = new LinkedList<MenuInfo>();
		Map<String, List<MenuInfo>> secondLevelMenuMap = new LinkedHashMap<String, List<MenuInfo>>();
		Map<String, List<MenuInfo>> thirdLevelMenuMap = new LinkedHashMap<String, List<MenuInfo>>();
		for (MenuInfo menuInfo: superiorMenuInfoList) {
			if (menuInfo.getMenuLevel() == 1) {
				firstLevelMenuList.add(menuInfo);
			}
			else if (menuInfo.getMenuLevel() == 2) {
				List<MenuInfo> secondLevelMenuList = secondLevelMenuMap.get(menuInfo.getMenuParentId().toString());
				if (secondLevelMenuList == null) {
					secondLevelMenuList = new LinkedList<MenuInfo>();
					secondLevelMenuList.add(menuInfo);
				} else {
					secondLevelMenuList.add(menuInfo);
				}
				secondLevelMenuMap.put(menuInfo.getMenuParentId().toString(), secondLevelMenuList);
			}
			else if (menuInfo.getMenuLevel() == 3) {
				List<MenuInfo> thirdLevelMenuList = thirdLevelMenuMap.get(menuInfo.getMenuParentId().toString());
				if (thirdLevelMenuList == null) {
					thirdLevelMenuList = new LinkedList<MenuInfo>();
					thirdLevelMenuList.add(menuInfo);
				} else {
					thirdLevelMenuList.add(menuInfo);
				}
				thirdLevelMenuMap.put(menuInfo.getMenuParentId().toString(), thirdLevelMenuList);
			}
		}
		
		// 返回
		model.addAttribute("id", id);
		model.addAttribute("authorityMenuIdSet", authorityMenuIdSet);
		model.addAttribute("firstLevelMenuList", firstLevelMenuList);
		model.addAttribute("secondLevelMenuMap", secondLevelMenuMap);
		model.addAttribute("thirdLevelMenuMap", thirdLevelMenuMap);

		return "/platmanager/menuAuthority";
	}
	
	/**
	 * 功能授权
	 * @param model
	 * @param id 平台用户ID
	 * @param menuId 新菜单ID
	 * @return
	 */
	@RequestMapping(value = "/menuAuthority", method = RequestMethod.POST)
	public String doMenuAuthority(ModelMap model,  Integer id, Integer[] menuId) {
		menuUserService.authMenu(id, menuId);
		return "redirect:/platmanager/manageList";
	}
	
	/**
	 * 加载接收人
	 * @param receiverType 接收类型
	 * @param userType 在新增工单页面或处理页面获得（1:代理商角色,2:运营中心部门,3:总部或总部下级部门）
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/loadReceiver", method=RequestMethod.POST)
	public Object loadReceiver(Integer receiverType, Integer userType) {
		if (receiverType == null) {
			return ERROR("empty");
		} else {
			PlatManager loginUser = super.getLoginUser();
			// 上级(非子账号代理商用自己，子账号代理商用上级)
			PlatManager superior = null;
			if (userType == 1 || userType == 2) {
				if (loginUser.getIsSubAccount() != null && loginUser.getIsSubAccount().intValue() == 1) {
					// 子账号， 找上级
					superior = platManagerService.findOne(loginUser.getSuperiorId());
				} else {
					// 上级，不变
					superior = loginUser;
				}
			}
			Integer groupId = super.superiorGroupId();
			
			Map<String, String> receiverMap = null;
			List<PlatGroup> platGroupList = null;
			List<PlatManager> platManagerList = null;
			switch (receiverType) {
				case 1: 
					/* 同 case 3 */
				case 3: 
					platManagerList = platManagerService.findInnerUser4HeadQuarter();
					receiverMap = platManagerList.stream().collect(Collectors.toMap(e -> e.getId().toString(), PlatManager::getNickName));
					break;
				case 2: 
					/* 同 case 9 */
				case 4: 
					/* 同 case 9 */
				case 7: 
					/* 同 case 9 */
				case 9: 
					platGroupList = platGroupService.findByGroupCodeStartingWith("HEADQUARTERS_");
					receiverMap = platGroupList.stream().collect(Collectors.toMap(e -> e.getGroupId().toString(), PlatGroup::getGroupName));
					break;
				case 5: 
					platManagerList = platManagerService.findAgentManager4HeadQuarter();
					receiverMap = platManagerList.stream().collect(Collectors.toMap(e -> e.getId().toString(), PlatManager::getNickName));
					break;
				case 6: 
					platManagerList = platManagerService.findOperationCenterManager();
					receiverMap = platManagerList.stream().collect(Collectors.toMap(e -> e.getId().toString(), PlatManager::getNickName));
					break;
				case 8: 
					/* 同 case 10 */
				case 10: 
					platManagerList = platManagerService.findInnerUser4OperationCenter(groupId, superior.getId());
					receiverMap = platManagerList.stream().collect(Collectors.toMap(e -> e.getId().toString(), PlatManager::getNickName));
					break;
				case 11: 
					platManagerList = platManagerService.findAgentManager4OperationCenter(groupId);
					receiverMap = platManagerList.stream().collect(Collectors.toMap(e -> e.getId().toString(), PlatManager::getNickName));
					break;
				case 12: 
					/* 同 case 14 */
				case 14: 
					platGroupList = platGroupService.findByUserId(superior.getId());
					receiverMap = platGroupList.stream().collect(Collectors.toMap(e -> e.getGroupId().toString(), PlatGroup::getGroupName));
					break;
				case 13: 
					/* 同 case 15 */
				case 15: 
					platManagerList = platManagerService.findInnerUser4Agent(superior.getId());
					receiverMap = platManagerList.stream().collect(Collectors.toMap(e -> e.getId().toString(), PlatManager::getNickName));
					break;
				default :
					break;
			}
			if (receiverMap != null) {
				return SUCCESS(receiverMap);
			} else {
				return ERROR("没有查询到数据");
			}
		}
	}
	
	
	@RequestMapping(value = "/treeview", method = RequestMethod.GET)
	public String treeview(ModelMap model) {
		return "/taskmanager/list1";
	}
}
